<template>
  <div class="app">
    <header>搏一搏单车变摩托</header>
    <Money :money="money"/>
    <Disc :discArr="discArr"/>
    <Pledge :pledgeMoney="pledgeMoney" @changePledgeMoney="changePledgeMoney"/>
    <Foot @start="start"/>
  </div>
</template>

<script>
import Disc from './components/disc.vue'
import Foot from './components/foot_1.vue'
import Money from './components/money_1.vue'
import Pledge from './components/pledge_1.vue'
export default {
  data () {
    return {
      money: 1000, // 全部资产
      discArr: [1, 3, 5], // 骰子
      pledgeMoney: 0 // 下注金额
    }
  },
  methods: {
    // 修改下注金额
    changePledgeMoney (num) {
      this.pledgeMoney = num
    },
    // 下注
    start (info) {
      if (this.money <= 0) {
        return alert('余额不足，快去充值吧')
      } else if (this.pledgeMoney > this.money) {
        this.pledgeMoney = 0
        return alert('想玩的大一些，那就快去充值吧')
      } else if (this.pledgeMoney <= 0) {
        return alert('请先下注')
      }
      this.playDisc(info)
    },
    // 让骰子动起来
    playDisc (info) {
      let time = 0
      // 开始摇骰子
      const timer = setInterval(() => {
        // 定义空数组存骰子的新数据
        const arr = []
        // 遍历骰子生成随机数
        for (let i = 0; i < this.discArr.length; i++) {
          const n = Math.floor(Math.random() * 6 + 1)
          arr.push(n)
        }
        this.discArr = arr
        time += 200
        if (time > 3000) {
          clearInterval(timer)
          // 判断是输了还是赢了
          // info为组件传来自己压的是哪个
          if (info.text === this.discResult()) {
            // 赢了
            if (info.text === '大') {
              this.money += this.pledgeMoney
            } else if (info.text === '小') {
              this.money += this.pledgeMoney
            } else if (info.text === '豹子') {
              this.money += this.pledgeMoney * info.ratio
            }
          } else {
            // 输了
            this.money -= this.pledgeMoney
          }
          this.pledgeMoney = 0
          console.log('骰子结果', this.discResult())
        }
      }, 300)
    },
    // 骰子的结果
    discResult () {
      // 数组去重，判断结果是什么
      const arr = [...new Set(this.discArr)]
      if (arr.length === 1) {
        return '豹子'
      }
      const sum = this.discArr.reduce((pre, val) => pre + val, 0)
      if (sum >= 12) return '大'
      return '小'
    }
  },
  // 注册组件
  components: {
    Disc,
    Foot,
    Money,
    Pledge
  }
}
</script>

<style lang="less">
*{
  padding: 0;
  margin: 0;
  list-style: none;
  box-sizing: border-box;
}
html,body{
  width: 100%;
  height: 100%;
}
.app{
  width: 100%;
  height: 100%;
}
header{
  width: 100%;
  height: 50px;
  background: #333;
  color: red;
  text-align: center;
  line-height: 50px;
}
</style>
